#! /usr/bin/env python

import platform
import configuration
import PyV8
import sys
import traceback
import glob

sys.path.append("dom/")
from window import *

# Depending on the given user agent, we select the appropriate
# JavaScript engine to use. We may need to have a 'default' engine
# as many engines (e.g., JavascriptCore) will not compile on some machines.
class Engine:
	def __init__(self, URL, script, HTML):
		self.engine = configuration.CURRENT_USER_AGENT['engine']
		self.script = script
		self.URL	= URL
		self.HTML   = HTML
		
		# Run the code
		self.execute()
		
	# Verifies that the selected engine can operate
	# on the current machine.
	def valid_engine(self):
		operating_system = platform.system()
				
		# The only engines that will run on Linux at the moment are
		# V8 and Spidermonkey. As such, if the OS is Linux, we dissalow
		# the execution of JScript and JavascriptCore (Webkit)
		if operating_system == "Linux":
			if self.engine == "jscript" or self.engine == "javascriptcore":
				return False
		
		return True
	
	# Prepares the JS for execution. Prepends the DOM and 
	# vulnerability modules if allowed
	def prepare(self):
		# If allowed, add vulnerability modules
		if configuration.PREPEND_VULNS:
			vulnerability_modules = glob.glob("vulnerabilities/*")
			
			for vulnerability in vulnerability_modules:
				f    = open(vulnerability, "r")
				code = f.read()
				self.script = code + self.script + "\n"
			
		# Replace CDATA tags so that it will not fail in the JS engines
		#self.script = self.script.replace("CDATA", "TEST")
		
	# Interacts with PyV8 to execute in Google's V8 Engine
	def v8(self):
		try:	
			ctxt = PyV8.JSContext(Window_Object(self.URL, self.HTML, "google.com"))
			ctxt.enter()
			ctxt.eval(self.script)
		except:
			print "[*] Error executing on V8 engine."
			traceback.print_exc(file=sys.stdout)
		
	# Interacts with the JavascriptCore engine
	def javascript_core(self):
		pass
		
	# Interacts with the JScript engine
	def jscript(self):
		pass
		
	# Interacts with spidermonkey
	def spidermonkey(self):
		pass
		
	# Executes the JavaScript using the selected engine
	def execute(self):
		self.prepare()
		
		#if not self.valid_engine():
		#	print "\t--> Selected JS engine cannot be run on this platform. Changing to default engine."
		#	self.engine = configuration.DEFAULT_ENGINE
		#
		#print "\t--> Executing JavaScript in " + self.engine
		self.v8()
